package com.wd.jetpack.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;

import androidx.core.content.ContextCompat;

import com.wd.jetpack.R;
import com.wd.jetpack.model.data.DatabaseConstants;
import com.wd.jetpack.util.log4j.AppLogger;
import com.wd.jetpack.util.log4j.LogFileUtils;

import java.io.File;

public class SetHome {
    private static ApkInfo apkInfo = null;
    private static String root_path = "com.nuoshou.mvvm";

    //数据库路径
    public static File roomFilePath() {
        File dir = Environment.getExternalStoragePublicDirectory(root_path);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                Logger.INSTANCE.e("创建路径失败");
            }
        }
        File file = new File(dir, DatabaseConstants.DATABASE_DIRECTORY);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Logger.INSTANCE.e("创建路径失败");
            }
        }
        Logger.INSTANCE.i("room地址：= " + file.getPath());
        return file;
    }

    public static void checkWritePermission(Context context) throws Exception {
        int writeExternalStoragePermission = ContextCompat.checkSelfPermission(
                context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (writeExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
            throw new Exception(context.getResources().getString(
                    R.string.no_permission_write_external_storage));
        }
    }

    private static void set(String propertyName, String publicPath, Context context) throws Exception {
        File dir = Environment.getExternalStoragePublicDirectory(publicPath);
        if (!dir.exists())
            if (!dir.mkdirs())
                throw new Exception(String.format(
                        context.getResources().getString(R.string.fail_to_create_directory),
                        dir.getPath()
                ));
        System.setProperty(propertyName, dir.getCanonicalPath());
    }

    private static void setTemp(String propertyName, String publicPath, Context context) throws Exception {
        File dir = new File(context.getFilesDir(), publicPath);
        if (!dir.exists())
            if (!dir.mkdirs())
                throw new Exception(String.format(
                        context.getResources().getString(R.string.fail_to_create_directory),
                        dir.getPath()
                ));
        System.setProperty(propertyName, dir.getCanonicalPath());
    }


    public static void setHome(Context context) throws Exception {
        String DMB_HOME_PATH = root_path;
        checkWritePermission(context);
        ApkInfo appInfo = getAppInfo(context);
        String packageName = appInfo.getApkPackage();
        if (packageName != null) {
            String testHdHomePath = root_path;

            File hdHomeDir = Environment.getExternalStoragePublicDirectory(DMB_HOME_PATH);
            File testHdHomeDir = Environment.getExternalStoragePublicDirectory(testHdHomePath);
            if (hdHomeDir.exists() && !testHdHomeDir.exists()) {
                LogFileUtils.copyDirectiory(hdHomeDir, testHdHomeDir, null);
            }

            DMB_HOME_PATH = testHdHomePath;
        }

        set("DMB_HOME", DMB_HOME_PATH, context);
        setTemp("DMB_HOME", DMB_HOME_PATH + "/temp", context);
        AppLogger.initConfig();
    }


    private static ApkInfo getAppInfo(Context ctx) {
        if (apkInfo == null) {
            try {
                apkInfo = new ApkInfo();
                PackageInfo packageInfo = ctx.getApplicationContext().getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    apkInfo.setVersionCode("" + packageInfo.getLongVersionCode());
                } else {
                    apkInfo.setVersionCode("" + packageInfo.versionCode);
                }
                apkInfo.setVersionName(packageInfo.versionName);
                apkInfo.setApkPackage(packageInfo.packageName);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        return apkInfo;
    }
}
